package xyz.kongbai121.demo.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import xyz.kongbai121.demo.domain.User;
import xyz.kongbai121.demo.mapper.UserMapper;
import xyz.kongbai121.demo.service.ILoginService;
import xyz.kongbai121.demo.util.UserPowerException;

import java.util.UUID;
import java.util.concurrent.TimeUnit;

@Service
@Transactional
public class LoginServiceImpl implements ILoginService {

    @Autowired
    private UserMapper userMapper;
    @Autowired
    private StringRedisTemplate redisTemplate;

    @Override
    public String login(User user) {
        QueryWrapper<User> wrapper = new QueryWrapper<>();
        wrapper.eq("openid",user.getOpenid());
        Integer count = userMapper.selectCount(wrapper);
        if (count == 0){
            //TODO 数据库没有则保存(注册)
            userMapper.insert(user);
        }
        String token = UUID.randomUUID().toString().replaceAll("-","");
        //TODO 生成令牌并返回给用户
        redisTemplate.opsForValue().set(token,user.getOpenid(),30, TimeUnit.MINUTES);
        return token;
    }

    @Override
    public User register(String token , String nickName, String avatarUrl, String gender, String province) {
        String openid = redisTemplate.opsForValue().get(token);
        if (openid != null && !openid.equals("")){
            User oldUser = userMapper.selectOne(new QueryWrapper<User>().eq("openid", openid));
            User user = new User(openid, nickName, avatarUrl, gender, province);
            //判断用户信息与数据库数据是否一致
            if (!oldUser.equals(user)){
                //TODO 更新用户信息
                oldUser.setNickName(nickName);
                oldUser.setAvatarUrl(avatarUrl);
                oldUser.setGender(gender);
                oldUser.setProvince(province);
                userMapper.updateById(oldUser);
            }
            return userMapper.getUser(user.getOpenid());
        }
        throw new UserPowerException("服务器异常");
    }

    @Override
    public String logout(String token) {
        try {
            //TODO Redis中的令牌
            redisTemplate.delete(token);
            return "退出成功";
        } catch (Exception e) {
            e.printStackTrace();
            return "";
        }
    }

    @Override
    public String delayed(String token) {
        try {
            //TODO 延长令牌有效期
            redisTemplate.expire(token,30,TimeUnit.MINUTES);
            return "续命成功";
        } catch (Exception e) {
            e.printStackTrace();
            return "未知错误";
        }
    }

    @Override
    public User getUserInfo(String token) {
        String openid = redisTemplate.opsForValue().get(token);
        return userMapper.getUser(openid);
    }
}
